package com.hy.demo.learn.server;

import com.hy.demo.model.constant.Constant;
import com.hy.demo.model.enums.DirectionEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * <p>
 *
 * </p>
 *
 * @author cjl
 * @version 1.0
 * @since 2020-08-11 13:49
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class StationHandler extends SimpleChannelInboundHandler<Object> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println(msg.toString());

        String[] data = StringUtils.split(msg.toString(), ",");

        // 帧头
        if (!StringUtils.equals(Constant.BEGIN, data[0])) {
            log.error("{}", "帧头不匹配");
            return;
        }

        // 心跳
        if (StringUtils.equals("-1", data[2])) {
            StringBuilder sb = new StringBuilder();

            //$GPRS,1,-1,?,n,OK,$END$
            sb.append(Constant.BEGIN + ",").append(DirectionEnum.SERVER_RESPONSE.getCode()).append(",").append("-1,").append("n,").append("?,").append("OK,")
                .append(Constant.END);
            // 处理接收内容
            String response = data[5];

            ctx.writeAndFlush(sb);
        }
        // 注册
        else if (StringUtils.equals("1", data[2])) {
            // 设备号;版本号
            String response = data[5];
            ctx.writeAndFlush("OK");
        }

        // 到站信息
        // 方向
        // 指令名称
        // 指令序号
        // 数据长度
        // 数据内容
        // 帧尾
    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inSocket.getAddress().getHostAddress();
        System.out.println(clientIP + "：连接成功");
        super.channelActive(ctx);
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inSocket.getAddress().getHostAddress();
        System.out.println(clientIP + "：离线");
        Channel channel = ctx.channel();
        if (channel != null) {
            channel.close();
            ctx.close();
        }
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        log.error("{}", cause.getMessage());
        cause.printStackTrace();
    }
}
